package com.modularity.project.video.ijk;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.SeekBar;

import androidx.appcompat.widget.AppCompatSeekBar;

import com.modularity.common.base.BaseActivity;
import com.modularity.common.utils.managers.manager.BarManager;
import com.modularity.common.utils.managers.manager.LogManager;
import com.modularity.project.R;

import java.util.ArrayList;
import java.util.List;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class IJKPlayerActivity extends BaseActivity {
    private IjkVideoView mVideoView;
//    private String videoNetUrl = "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8";
    private String videoNetUrl = "http://lk-upload.oss-cn-hangzhou.aliyuncs.com/knowledge/2de2e444-df92-41aa-94d1-addf135f46b2.mp4?Expires=1987555591&OSSAccessKeyId=LTAIlP1AgX0kaxVA&Signature=j%2BAhBVLHbzm58upThOhIHLhfaQU%3D";
    private String videoNetUrl1 = "http://hls.cntv.lxdns.com/asp/hls/main/0303000a/3/default/978a64ddd3a1caa85ae70a23414e6540/main.m3u8";
    //    private String videoNetUrl2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear4/prog_index.m3u8";
    //    private String videoNetUrl2 = "http://kbs-dokdo.gscdn.com/dokdo_300/_definst_/dokdo_300.stream/playlist.m3u8";
    private final List<String> videoList = new ArrayList<>();
    private int currentIndex = 0;
    private AppCompatSeekBar seekBar;
    private int curSeekPos = -1;
    private int curSeekCount = 0;
    private Handler playProgressHandler;
    private final int MSG_REFRESH = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarManager.setNavBarVisibility(this, false);
        BarManager.setStatusBarVisibility(this, false);
        videoList.add(videoNetUrl);
        videoList.add(videoNetUrl1);
//        videoList.add(videoNetUrl2);
        setContentView(R.layout.activity_ijk);
        findViewById(R.id.btn_change).setOnClickListener(view -> change());
        findViewById(R.id.btn_play).setOnClickListener(view -> play());
        findViewById(R.id.btn_pause).setOnClickListener(view -> pause());
        findViewById(R.id.btn_close).setOnClickListener(view -> finish());
        initVideoView(videoNetUrl);
        initSeekBar();
        initPlayProgressHandler();
    }

    private void initPlayProgressHandler() {
        playProgressHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_REFRESH:
                        if (mVideoView.isPlaying()) {
                            refreshProgress();
                            playProgressHandler.sendEmptyMessageDelayed(MSG_REFRESH, 1000);
                        }

                        break;
                }

            }
        };
    }

    private void initSeekBar() {
        seekBar = findViewById(R.id.seek_bar);
        seekBar.setMax(100);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                playProgressHandler.removeCallbacksAndMessages(null);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                long duration = mVideoView.getDuration();
                long newPosition = (duration * seekBar.getProgress()) / 100L;
                mVideoView.seekTo(newPosition);
                curSeekPos = (int) newPosition;
            }
        });
    }

    private void change() {
        if (currentIndex == 1) {
            currentIndex = 0;
        } else {
            currentIndex++;
        }
        mVideoView.stop();
        mVideoView.reset();
        mVideoView.setPath(videoList.get(currentIndex));
        play();
    }

    private void refreshProgress() {
        long current = mVideoView.getCurrentPosition() / 1000L;
        long duration = mVideoView.getDuration() / 1000L;
//        long current_second = current % 60;
//        long current_minute = current / 60;
//        long total_second = duration % 60;
//        long total_minute = duration / 60;
//        String time = current_minute + ":" + current_second + "/" + total_minute + ":" + total_second;
//        LogManager.iTag("jishen", "time:" + time);
        LogManager.iTag("jishen", "current:" + current);
        LogManager.iTag("jishen", "duration:" + duration);
        if (duration != 0) {
            seekBar.setProgress((int) (current * 100 / duration));
        }

    }

    private void play() {
        mVideoView.start();
    }

    private void pause() {
        mVideoView.pause();
    }

    private void initVideoView(String videoUrl) {
        mVideoView = findViewById(R.id.ijkVideoView);
        mVideoView.setListener(new IjkVideoView.VideoPlayerListener() {
            @Override
            public void onVideoSizeChanged(IMediaPlayer iMediaPlayer, int i, int i1, int i2, int i3) {
                LogManager.iTag("jishen", "onVideoSizeChanged：i=" + i + " i1=" + i1 + " i2=" + i2 + " i3=" + i3);
            }

            @Override
            public void onSeekComplete(IMediaPlayer iMediaPlayer) {
                LogManager.iTag("jishen", "onSeekComplete");
            }

            @Override
            public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
                LogManager.iTag("jishen", "onInfo:i=" + i + " i1=" + i1);
                return false;
            }

            @Override
            public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {
                LogManager.iTag("jishen", "onBufferingUpdate：" + i);
            }

            @Override
            public void onPrepared(IMediaPlayer mp) {
                LogManager.iTag("jishen", "onPrepared");
                //播放成功处理
                mp.start();
                playProgressHandler.sendEmptyMessageDelayed(MSG_REFRESH, 0);
            }

            @Override
            public void onCompletion(IMediaPlayer iMediaPlayer) {
                LogManager.iTag("jishen", "onCompletion");
            }

            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                LogManager.iTag("jishen", "onError");
                return false;
            }
        });
        mVideoView.setPath(videoUrl);
        mVideoView.start();
    }

    @Override
    protected void initData() {
        super.initData();
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
    }

    @Override
    protected void onStop() {
        super.onStop();
        pause();
        playProgressHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.stop();
        mVideoView.release();
        IjkMediaPlayer.native_profileEnd();
    }
}
